// src\views\sendbox\right-manage\RightList.jsx
// 权限列表
import React, { useEffect, useState, useRef } from 'react'
import { Space, Table, Button, Modal, message, Input, Switch, Form, Select } from 'antd';
import { EditOutlined, DeleteOutlined, UserAddOutlined } from '@ant-design/icons'
import axios from 'axios';
export default function UserList() {
  // 监听列表的刷新
  const [isRefresh, setIsRefresh] = useState(false);
  const [dataSource, setdataSource] = useState([]);
  const [isModalOpen, setisModalOpen] = useState(false);
  const [form] = Form.useForm();
  const { Option } = Select;
  const formRef = useRef(null)
  // 区域列表
  const [regionsList, setRegionsList] = useState([]);
  // 角色列表
  const [rolesList, setRolesList] = useState([]);
  // 初始化从模拟接口获取到动态的导航菜单数据
  useEffect(() => {
    axios.get('http://localhost:8888/users?_expand=role').then(res => {
      // console.log("get导航数据", res.data);
      setdataSource(res.data);
    })
  }, [isRefresh]);
  useEffect(() => {
    // 请求区域
    axios.get('http://localhost:8888/regions').then(res => {
      setRegionsList(res.data);
    });
    // 请求角色列表
    axios.get('http://localhost:8888/roles').then(res => {
      setRolesList(res.data);
    })
  }, [])
  const switchPermisson = (item) => {//改变数据权限
    item.roleState = !item.roleState;
    axios.patch(`http://localhost:8888/users/${item.id}`, {
      roleState: item.roleState
    });
    setIsRefresh(!isRefresh);
  }
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      key: 'region',
      filters: [
        ...regionsList.map(e => ({
          text: e.title,
          value: e.value
        })),
        {
          text: "全球",
          value: "全球"
        }
      ],
      onFilter: (value, item) => {
        console.log(value, item);
        if (value === '全球') {
          return item.region === '';
        } else {
          return item.region === value;
        }
      }

    },
    {
      title: '用户名称',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      key: 'role',
      render: (role) => {
        return role.roleName
      }
    }, {
      title: '用户状态',
      dataIndex: 'roleState',
      key: 'roleState',
      render: (roleState, item) => {
        return <Switch defaultChecked={roleState} disabled={item.default} onChange={() => switchPermisson(item)} />
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, item) => {
        return (
          <Space>
            <Button type="primary" danger shape="circle" disabled={item.default} icon={<DeleteOutlined />} size="small" onClick={() => deleteUser(item)} />
            <Button type="primary" shape="circle" disabled={item.default} icon={<EditOutlined />} size="small" onClick={() => editUser(item)} />
          </Space>
        )
      }
    },
  ];
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [currItem, setCurrItem] = useState({});
  const deleteUser = (item) => {
    // console.log("点击删除", item);
    setCurrItem(item);
    setOpen(true);
  }
  const editUser = (item) => {
    setCurrItem(item);
    setisModalOpen(true);
    formRef.current.setFieldsValue({ ...item });
  }
  const handleOk = () => {
    setConfirmLoading(true);
    axios.delete(`http://localhost:8888/users/${currItem.id}`).then(res => {
      if (res.status === 200) {
        message.success("删除成功")
      } else {
        message.warning("删除失败")
      }
    })
    setOpen(false);
    setIsRefresh(!isRefresh);
    setConfirmLoading(false);
  };
  const handleAddToOk = () => {
    formRef.current.validateFields().then(value => {
      console.log("handleAddToOk", value, currItem);
      if (currItem.id) {//修改
        axios.patch(`http://localhost:8888/users/${currItem.id}`,Object.assign(currItem,value));
      } else {
        axios.post('http://localhost:8888/users', {
          ...value,
          "roleState": true,
          "default": false,
        }).then(res => {
          setIsRefresh(!isRefresh);
         
          message.success("添加成功!");
        })
      }
      formRef.current.resetFields();
      setisModalOpen(false);

    }).catch(err => console.log("err", err));


  }

  const handleCancel = () => {
    setOpen(false);
    setisModalOpen(false);
  };
 
  const onGenderChange = (value) => {
    console.log("onGenderChange-----", value);
  };
  return (
    <div>
      <Button style={{ marginBottom: '20px' }} type="primary" onClick={() => { setisModalOpen(true) }} icon={<UserAddOutlined />}>
        添加用户
      </Button>
      {/* 新增弹框 */}
      <Modal title="添加用户" open={isModalOpen} onOk={handleAddToOk} onCancel={handleCancel} okText="确定"
        cancelText="取消" width={400}>
        <Form
          layout="horizontal"
          form={form}
          ref={formRef}
        >
          <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名', }]}>
            <Input placeholder="输入用户名" />
          </Form.Item>
          <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码', }]}>
            <Input placeholder="输入密码" />
          </Form.Item>
          <Form.Item
            name="region"
            label="区域"
          >
            <Select
              placeholder="选择一个区域"
              onChange={onGenderChange}
              allowClear
            >
              {
                regionsList.map(e => { return <Option key={e.id} value={e.title}>{e.title}</Option> })
              }
            </Select>
          </Form.Item>
          <Form.Item
            name="roleId"
            label="角色"
            rules={[{ required: true, message: "请选择一个角色" }]}
          >
            <Select
              placeholder="选择一个角色"
              onChange={onGenderChange}
              allowClear
            >
              {
                rolesList.map(e => { return <Option key={e.id} value={e.id}>{e.roleName}</Option> })
              }
            </Select>
          </Form.Item>
        </Form>
      </Modal>
      {/* 列表 */}
      <Table dataSource={dataSource} columns={columns} rowKey="id" />
      <Modal
        title="删除"
        open={open}
        onOk={handleOk}
        okText="确定"
        cancelText="取消"
        confirmLoading={confirmLoading}
        onCancel={handleCancel}

      >
        <p>
          确认删除？
        </p>
      </Modal>
    </div>
  )
}
